package com.mills.gamebase.web;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.mills.gamebase.service.Dict;
import com.mills.gamebase.service.GamebaseUtils;
import com.mills.gamebase.service.ServletContextHolder;
import com.mills.gamebase.service.SessionUtils;

@Controller
public class BannerController {
	
	private Logger logger = Logger.getLogger(BannerController.class);

	@RequestMapping("/banner/overview.htm")
	public ModelAndView overview (HttpServletRequest request) {
		ModelMap map = new ModelMap();
		map.addAttribute(Dict.MM_CONTENT, "banner/overview.jsp");
		SessionUtils.addStylesheet(request.getSession(), "banner/overview.css");
		SessionUtils.addJavascript(request.getSession(), "fileupload.js");
		
		// Das Banner Verzeichnis �ffnen
		File resourcesDir = new File(ServletContextHolder.getInstance().getServletContext().getRealPath("/resources/data/banner"));
		// Pr�fen, ob das Verzeichnis exisiert und ein Verzeichnis ist 
		if (resourcesDir.exists() && resourcesDir.isDirectory()) {
			// Alle Dateien mit akzptierten Bildformaten zur�ckgeben
			String[] files = resourcesDir.list(new FilenameFilter(){
													public boolean accept(File dir, String name) {
														// Die Liste aller akzeptierten Bildformate laden
														@SuppressWarnings("unchecked")
														List<String> formatList = (List<String>) GamebaseUtils.getBeanByName("MyAcceptedImageFormatsList");
														// Pr�fen, ob die Datei von einem der akzeptierten Typen ist
														for (String format : formatList) {															
															if (name.endsWith(format)) return true;
														}
														// Ist die Datei nicht von einem akzeptierten Format, so wird sie ignoriert
														return false;
												}});
			
			map.addAttribute("banner", files);
		}
		
		return new ModelAndView("index", map);
	}
	
	@RequestMapping("/banner/fileupload.htm")
	public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		try {
            @SuppressWarnings("unchecked")
			List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) {
                if (item.getFieldName().equals("file")) {
                    String filename = FilenameUtils.getName(item.getName());
                    String responseMsg = "";
                    
                    boolean supported = checkBannerSupport(filename);
					
					if (supported) {
						if (logger.isDebugEnabled()) {
							logger.debug("'" + filename + "' is supported.");
						}
						
						GamebaseUtils.uploadFile(item, "/resources/data/banner/");
						
						if (logger.isDebugEnabled()) {
							logger.debug("Done uploading.");
						}
						
						responseMsg = "File " + filename + " successfully uploaded";			
					} else {
						if (logger.isDebugEnabled()) {
							logger.debug("'" + filename + "' is not supported.");
						}
						responseMsg = "File " + filename + " is of not supported type";
					}
					
					response.setContentType("text/plain");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(responseMsg);	
                    return;
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException("Parsing file upload failed.", e);
        }
	}

	/**
	 * Pr�ft, ob der Dateityp f�r Banner supported ist
	 * 
	 * @param filename
	 * @return
	 */
	private boolean checkBannerSupport(String filename) {
		boolean supported = false;
		if (logger.isDebugEnabled()) {
			logger.debug("Checking if '" + filename + "' is of supported type...");
		}

		// Die Liste aller akzeptierten Bildformate laden
		@SuppressWarnings("unchecked")
		List<String> formatList = (List<String>) GamebaseUtils.getBeanByName("MyAcceptedImageFormatsList");
		
		for (String format : formatList) {
			if (filename.endsWith(format)) {
				supported = true;
				break;
			}
		}
		return supported;
	}
}
